#ifndef CARDDETECTDLG_H
#define CARDDETECTDLG_H

#include <QWidget>
#include "cvutils.h"

namespace Ui {
class CardDetectDlg;
}

class DetectorThread : public std::enable_shared_from_this<DetectorThread>{
public:
    DetectorThread( CvUtils::cardCornerDetector* detector = nullptr);
    ~DetectorThread();
    QThread* thread() {return m_detectThread;}
private:
    QThread* m_detectThread;
};

class CardDetectDlg : public QWidget
{
    Q_OBJECT

public:
    explicit CardDetectDlg(QWidget *parent = nullptr);
    ~CardDetectDlg();
    void showScanRes(const char *frontPath, const char *backPath);

public slots:
    void modelLoaded(bool success, const QString& message);
    void errorOccurred(const QString& errorMsg);
    void process(const std::vector<CardDetectionResult>& fresults,
                 const std::vector<CardDetectionResult>& bresults);

    void visualize(const cv::Mat& fvisualizedImage,
                   const cv::Mat& bvisualizedImage);
private slots:
    void on_ExportBtn_clicked();

private:
    Ui::CardDetectDlg *ui;
    std::unique_ptr<CvUtils::cardCornerDetector> m_detector;
    std::unique_ptr<DetectorThread> m_detectThread;
    cv::Mat m_originFront;  // 保存原始正面图像
    cv::Mat m_originBack;   // 保存原始反面图像
    QPixmap m_preview;
    bool m_isModelLoaded = false; // 主线程的模型加载标志
    QString m_frontPath;  // 保存正面图片路径
    QString m_backPath;   // 保存反面图片路径
    bool m_pathsReady = false; // 标记路径是否已设置

    // 辅助函数：将cv::Mat转换为QPixmap
    QPixmap cvMatToQPixmap(const cv::Mat& mat) {
        if (mat.empty()) return QPixmap();

        cv::Mat rgbMat;
        if (mat.channels() == 1) {
            cv::cvtColor(mat, rgbMat, cv::COLOR_GRAY2RGB);
        } else {
            cv::cvtColor(mat, rgbMat, cv::COLOR_BGR2RGB);
        }

        QImage img(rgbMat.data, rgbMat.cols, rgbMat.rows,
                   rgbMat.step, QImage::Format_RGB888);
        return QPixmap::fromImage(img);
    }

    // 辅助函数：对证件进行透视变换矫正
    cv::Mat correctPerspective(const cv::Mat& image, const std::vector<cv::Point2f>& corners);

    // 新增：统一触发检测的函数（内部校验双条件）
    void triggerDetection();
};

#endif // CARDDETECTDLG_H
